<?php 

if (!$this->form) return;

$show = 0;
$elements = $this->form->getElements();
foreach ($elements as $element) {
	if ($element->getAttrib('class') == 'crud_listbox') {
		$show = 1;
	}
}

if (!$show) {
	return;
}

?>


<script type='text/javascript' template='<?php echo basename(__FILE__); ?>'>
$(function() {

	function initListbox($box) {
		var $value = '';
		var $options = $box.find("option");
		var $selected = $options.filter(':selected');
		
		$selected.each(function() {
			if ($value) {
				$value += ', ';
			}
			
			$value += $(this).text();
		});

		$box.prev().prev().val($value);
	}
	
	$(".crud_listbox").each(function() {
		var $box = $(this);
		var $name = $box.attr("name");
		var $edit = $("<input type='text' size='128' />").addClass('control_crud_listbox');
		
		$box.before($edit);
		$box.before("<br />");
		$edit.before("<div />");
		
		initListbox($box);
	});

	$(".crud_listbox").click(function() {
		initListbox($(this));
	});

	$(".control_crud_listbox").live('keyup', function() {
		var $self = $(this);
		var $value = $self.val();

		var $words = explode(',', $value);
		$words = $($words);
		var $options = $self.next().next().find("option");
		$options.each(function() {
			$(this).removeAttr("selected");
		});

		$self.prev().html("");
		$words.each(function($index, $word) {
			var $match = 0;
			$word = $word.replace(/^\s\s*/, '').replace(/\s\s,*$/, '');
			$word = strtolower($word);
			$options.each(function() {
				var $option = $(this);
				if (strtolower($option.attr("label")) == $word) {
					$option.attr("selected", "selected");
					$match = 1;
				}
			});

			if (!$match && $word) {
				$self.prev().html("Введите слово из списка ниже. Слова `"+$word+"` там нет!");
			}
		});
		
	});

	function explode( delimiter, string ) {	// Split a string by string
		// 
		// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: kenneth
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

		var emptyArray = { 0: '' };

		if ( arguments.length != 2
			|| typeof arguments[0] == 'undefined'
			|| typeof arguments[1] == 'undefined' )
		{
			return null;
		}

		if ( delimiter === ''
			|| delimiter === false
			|| delimiter === null )
		{
			return false;
		}

		if ( typeof delimiter == 'function'
			|| typeof delimiter == 'object'
			|| typeof string == 'function'
			|| typeof string == 'object' )
		{
			return emptyArray;
		}

		if ( delimiter === true ) {
			delimiter = '1';
		}

		return string.toString().split ( delimiter.toString() );
	}

});
</script>